package com.shanyutiwen.springbootblogtest.dao;

import com.shanyutiwen.springbootblogtest.model.PostModel;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.List;

@Repository
public class PostDao {
    @Resource
    JdbcTemplate jdbcTemplate;

    public void savePost(PostModel postModel) {
        jdbcTemplate.update("insert into post (title, content, create_time, update_time) VALUES (?, ?, ?, ?)",
                postModel.getTitle(),
                postModel.getContent(),
                postModel.getCreateTime(),
                postModel.getUpdateTime()
        );
    }

    public void deletePost(Long id) {
        jdbcTemplate.update("delete from post where id = ? ", id);
    }

    /**
     * 查询单条数据
     * @param id Int
     * @return PostModel
     */
    public PostModel getPostById(Long id) {
        return jdbcTemplate.queryForObject(
                "select * from post where id = ?",
                new Object[]{id},
                new BeanPropertyRowMapper<>(PostModel.class)
        );
    }

    public List<PostModel> getAllPost() {
        return jdbcTemplate.query(
                "select * from post",
                new BeanPropertyRowMapper<>(PostModel.class)
        );
    }

    public void updatePostById(PostModel postModel) {
        jdbcTemplate.update(
                "update post set title = ?, content = ?, create_time = ?, update_time = ? where id = ?",
                postModel.getTitle(),
                postModel.getContent(),
                postModel.getCreateTime(),
                postModel.getUpdateTime(),
                postModel.getId()
        );
    }

    public void deletAllPost() {
        jdbcTemplate.update("delete from post where true");
    }
}
